<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\BusinessModel;
use App\Model\PriceOrdersModel;
use App\Model\WithdrawalModel;
use App\Services\Logger;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class BusinessesDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
            $query = BusinessModel::query();

            $query->when(checkIsHasField($params,'businesses_id'),function ($query)use ($params){
                $query->where('businesses_id',$params['businesses_id']);
            });

            $query->when(checkIsHasField($params,'show'),function ($query)use ($params){
                $query->where('show',$params['show']);
            });
            $query->when(!checkIsHasField($params,'orders'),function($query)use ($params){
                $query->orderByDesc('created_at');
            });
            return $query;
    }

    /**
     * @throws SysExceptions
     */
    public static function add($params = [])
    {
        checkForData(['password'],['请输入密码'],$params);
        $adminQuery = AdminDao::getAdminBuilderQuery([
            'username'=>$params['businesses_title']
        ]);
        if($adminQuery->exists()){
            self::error('账号已存在');
        }
        DB::beginTransaction();
        try {
            $params['time'] = strtotime(date('Y-m-d'));
            $result = self::builder_query()->create($params);
            //创建账号
            $adminQuery->create([
                'username'=>$params['businesses_title'],
                'password'=>password_hash($params['password'],PASSWORD_DEFAULT),
                'shop_id'=>$result->businesses_id,
                'menu_ids'=>'84,85,86,88,89,93'
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }



    public static function update($params = [])
    {
        DB::beginTransaction();
        try {
            $id = self::deleteParamId($params,'businesses_id');
            self::builder_query(['businesses_id'=>$id])->update(self::filterFields($params,new BusinessModel()));
            $update = [
                'username'=>$params['businesses_title'],
            ];
            if(checkIsHasField($params,'password')){
                $update['password'] = password_hash($params['password'],PASSWORD_DEFAULT);
            }
            //创建账号
            AdminDao::getAdminBuilderQuery([
                'shop_id'=>$id
            ])->update($update);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function delete($params = [])
    {
        DB::beginTransaction();
        try {
            $id = self::deleteParamId($params);
            self::builder_query(['businesses_id'=>$id])->delete();
            //创建账号
            AdminDao::getAdminBuilderQuery(['shop_id'=>$id])->delete();
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function businesses(array $params): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($params)->paginate();
    }

    public static function info(array $all)
    {
        return self::builder_query($all)->first()->toArray();
    }

    public static function nowPrice($priceB, $shop_id,$shopInfo)
    {
        //查询当前店铺有没有等待返佣的
        try {
            $lineQuery = LineUpPriceDao::builder_query([
                'shop_id'=>$shop_id,
                'status'=>0
            ]);


            if($lineQuery->exists()){
                $lineData = $lineQuery->first()->toArray();
                $price = bcmul($priceB,(1-$shopInfo['rate_buess']),2);
                //如果
                $status = 0;
                if(bcsub($lineData['money'],$lineData['now_price'],2) < $price){
                    $price = bcsub($lineData['money'],$lineData['now_price'],2);
                    $status = 1;
                }
                //给这个用户返费20%
                BillsDao::moneysUpdate($price,$lineData['user_id'],'消费返利奖励');
                $priceB = bcsub($priceB,$price,2);
                //增加现在的返佣
                $lineQuery->increment('now_price',$price);
                if($status == 1){
                    $lineQuery->update([
                        'status'=>1
                    ]);
                }
            }


            //共享股东

            //剩下的钱加到商家上
            BusinessesDao::builder_query([
                'businesses_id'=>$shop_id
            ])->increment('rate_price',$priceB);
        }catch (\Exception $exception){
            self::error($exception->getMessage());
        }

    }

    /**
     * @throws SysExceptions
     */
    public static function pay(array $params)
    {
        checkForData(['shop_id','price'],['请选择商铺','请输入金额'],$params);
        $order_code = makeOrderNo();
        $result = PriceOrdersModel::query()->create([
            'price'=>$params['price'],
            'user_id'=>$params['user_id'],
            'shop_id'=>$params['shop_id'],
            'order_code'=>$order_code
        ]);
        if(!$result){
            self::error('订单创建失败');
        }
        $shopName = self::builder_query([
            'businesses_id'=>$params['shop_id']
        ])->value('businesses_title');
        $userInfo = UsersDao::builder_query(['user_id'=>$params['user_id']])->first()->toArray();
        $dataResult = PayServices::pay([
            'openid'=>$userInfo['openid'],
            'name'=>$shopName,
            'price'=>$params['price'],
            'order_code'=>$order_code,
            'notify_url'=>route('admin.notice_pay_price')
        ]);
        return $dataResult;
    }

    public static function everyPriceGive($pricesMoney, $businesses_id)
    {
        $listsCountU = LineUpPriceDao::builder_query([
            'shop_id'=>$businesses_id,
            'status'=>0
        ])->get()->toArray();
        if(empty($listsCountU)){
            Logger::everyDay('数据',[
                $pricesMoney
            ]);
            return;
        }

        //每个人给钱
        DB::beginTransaction();
        try {
            foreach ($listsCountU as $value){
                $dataIrtem = $pricesMoney;
                $status = 0;
                if($dataIrtem > ($value['money'] - $value['now_price'])){
                    $dataIrtem = ($value['money'] - $value['now_price']);
                    $status = 1;
                }

                $lineQuery = LineUpPriceDao::builder_query([
                    'line_up_price_id'=>$value['line_up_price_id']
                ]);
                BillsDao::moneysUpdate($dataIrtem,$value['user_id'],'每日消费返利奖励');
                //增加现在的返佣
                $lineQuery->increment('now_price',$dataIrtem);

                //奖励给每个人
                if($status == 1){
                    $lineQuery->update([
                        'status'=>$status
                    ]);
                }

                BusinessesDao::builder_query([
                    'businesses_id'=>$businesses_id
                ])->decrement('rate_price',$dataIrtem);
            }
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Logger::everyDay('错误'.$exception->getMessage(),[
                'shop_id'=>$businesses_id
            ]);
        }


    }

    public static function quitOrder(array $params)
    {
        //退出返现并且返费1%
        $lineQuery = LineUpPriceDao::builder_query([
            'line_up_price_id'=>$params['line_up_price_id'],
            'status'=>0
        ]);

        if(!$lineQuery->exists()){
            self::error('返现订单不存在!');
        }
        $lineInfo = $lineQuery->first()->toArray();
        $nowPrice = $lineInfo['money'] - $lineInfo['now_price'];
        if($nowPrice == 0){
            self::error('暂无返现');
        }
        $priceU = bcmul($nowPrice,0.01,2);
        //给用户并且设置订单完成
        DB::beginTransaction();
        try {
            $lineQuery->update([
                'status'=>1
            ]);
            BillsDao::moneysUpdate($priceU,$lineInfo['user_id'],'退出返现排队立即奖励');

            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }

    }

    public static function withs(array $params)
    {
        //查询商家
        $info = self::builder_query([
            'businesses_id'=>$params['shop_id']
        ])->first();
        if($info['money'] < $params['nums']){
            self::error('金额不足');
        }
        $dataFee = bcmul($params['nums'],0.1,2);
        //扣款并且创建到表
        DB::beginTransaction();
        try {
            SbillsDao::moneysUpdate(-($params['nums']),$params['shop_id'],'店铺提现');
            WithdrawalModel::query()->create([
                'card_json_data'=>json_encode([
                    'name'=>$params['name'],
                    'card_no'=>$params['card_no'],
                    'card_kai'=>$params['card_kai']
                ],JSON_UNESCAPED_UNICODE),
                'shop_id'=>$params['shop_id'],
                'fee'=>$dataFee,
                'nums'=>$params['nums']-$dataFee,
                'status'=>0
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }
}
